<?php
namespace app\shop\controller;

use \think\Controller;
use \think\Db;
class Index extends Base
{
    /**
     * 首页
     * @$page 分页
     * @return array 返回数组
     */
    public function index()
    {
		extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['order_shopid'] = $user_id;//公共条件
        $where['order_status'] = array('>',1);//公共条件
        //1、我的相关-----------------------------------------------
        $shop = Db::table('up_order')
            ->where($where)
            ->where('order_in_out', '<>',3)
            ->where('order_send_status', '>',0)
            ->whereTime('order_paytime', 'today')
            ->field('SUM(order_user_pay) as todayMoney,count(*) as todayOrder')
            ->find();
        $shop['s_integral'] = Db::table('up_shops')->where('s_id',$user_id)->find()['s_integral'];
        //2、今日订单-------------------------------------------------

        $field = 'order_id,order_number,order_paytime,order_send_status';
        $field .= ',order_address_name,order_address,order_address_phone';
        $field .= ',order_in_out,d_name,d_id,d_phone';
        $data = Db::table('up_order')->alias('o')
            ->join('up_shop_driver d','o.order_driver_id=d.d_id','LEFT')
            ->where($where)
//            ->where('order_in_out', '<>',3)
            ->where('order_send_status', '<',3)
//            ->whereTime('order_paytime', 'today')
            ->field($field)
            ->order('order_send_status ASC')
            ->page($page,10)
            ->select();
        //本月的，一共
        $shop['monthOrder'] = Db::table('up_order')
            ->where($where)
            ->where('order_in_out', '<>',3)
            ->where('order_send_status', '>',0)
            ->whereTime('order_paytime', 'm')
            ->count();
        $shop['allOrder'] = Db::table('up_order')
            ->where($where)
            ->where('order_in_out', '<>',3)
            ->where('order_send_status', '>',0)
            ->count();
        return json_encode(['status'=>200,'shop'=>$shop,'msg'=>$data]);
    }
    /**
     * 历史订单
     * $date，page
     * @return string
     */
    public function historyOrder()
    {
		extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['order_shopid'] = $user_id;//公共条件
        $where['order_status'] = array('>',1);//公共条件
        $where['order_paydate'] = $date;//公共条件
        $field = 'order_id,order_number,order_paytime,order_send_status';
        $field .= ',order_address_name,order_address,order_address_phone';
        $field .= ',order_in_out,d_name,d_id,d_phone';
        $data = Db::table('up_order')->alias('o')
            ->join('up_shop_driver d','o.order_driver_id=d.d_id','LEFT')
            ->where($where)
//            ->where('order_in_out', '<>',3)
//            ->where('order_send_status', '>',0)
            ->field($field)
            ->order('order_send_status ASC')
            ->page($page,10)
            ->select();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 订单详情：orderInfo
     * order_id
     * @return string
     */
    public function orderInfo()
    {
        extract(input());
        $auth = $this->checkAll(0,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['order_id'] = $order_id;
        $order = Db::table('up_order')->alias('o')
            ->join('up_shops s','o.order_shopid=s.s_id','LEFT')
            ->where($where)
            ->field('o.*,s.s_id,s.s_name,s_phone,s_thumb')
            ->find();
        $goods = Db::table('up_order_info')
            ->where('oi_order_id',$order_id)
            ->select();
        return json_encode(['status'=>200,'order'=>$order,'goods'=>$goods]);
    }
    /**
     * 接单或已送达：orderReciveAndOver
     * order_id，type（2是去配送，3是已送达）
     * @return string
     */
    public function orderReciveAndOver()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($type != 2 && $type != 3){
            return json_encode(['status'=>0,'msg'=>'传参错误！']);
        }
        $update = array();
        $update['order_send_status'] = $type;
        if($type == 2){//如果是2(配送员选择没)
            if(isset($driver_id)){
                $update['order_driver_id'] = $driver_id;
            }
        }
        if($type == 3){//如果是2(配送员选择没)
            $update['order_driver_status'] = 3;
        }
        $update['order_last_time'] = date('Y-m-d H:i:s');
        $where = array();
        $where['order_id'] = $order_id;
        $res = Db::table('up_order')->where($where)->update($update);
        if($res){
            if($type == 2){//如果是2(配送员选择没)
                if(isset($driver_id)){
                    //通知和推送
                    allInNotice('您有新的配送订单','您有新的配送订单，请注意查收',$driver_id);
                    try {
                        sendJpush("$driver_id", '您有新的配送订单，请注意查收', array('a' => 'b'), 2, 100, 2);
                    } catch(\Exception $e) {

                    }
                }
            }
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }

    }
    /**
     * 获得本店配送员：myDriver
     * @return string
     */
    public function myDriver()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['d_shop_id'] = $user_id;
        $res = Db::table('up_shop_driver')
            ->where($where)
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 退款：orderBack
     * order_id，type（3是同意，4是拒绝）
     * @return string
     */
    public function orderBack()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($type != 3 && $type != 4){
            return json_encode(['status'=>0,'msg'=>'传参错误！']);
        }
        $where = array();
        $where['order_id'] = $order_id;
        $update = array();
        $update['order_in_out'] = $type;
        Db::startTrans();
        try{
            $content = '您的退款申请被拒绝，如有疑问请联系店家';
            $content2 = '您的退款申请被拒绝';
            if($type == 3){
                $content = '您的退款申请已同意，请注意查收';
                $content2 = '您的退款申请已同意';
                $payinfo = Db::table('up_order')->where($where)
                    ->field('order_user_pay money,order_number number,order_back_transaction_id transaction_id,order_in_out,order_type,order_where,order_shopid')
                    ->find();
                if($payinfo['order_in_out'] == 3){
                    return json_encode(['status'=>0,'msg'=>'请勿重复操作']);
                }
                $shopmoney = Db::table('up_shops')->where('s_id', $payinfo['order_shopid'])->value('s_money');
                if($payinfo['money'] > $shopmoney){
                    return json_encode(['status'=>0,'msg'=>'您商铺的余额不足！']);
                }
                if($payinfo['order_type'] == 1){
                    $back = $this->refund($payinfo);
                }else{
                    if($payinfo['order_where'] == 1){
                        $back = $this->refundWx($payinfo);
                    }else{
                        $tui = new \app\home\controller\Car();
                        $back = $tui->WeChatTuikuan($payinfo);
                    }
                }

                if($back['status'] != 200){
                    return json_encode(['status'=>0,'msg'=>$back['msg']]);
                }else{
                    $order = Db::table('up_order')->where($where)
                        ->field('order_id,order_user_pay,order_shopid')
                        ->find();
                    $money = Db::table('up_shops')->where('s_id', $order['order_shopid'])->value('s_money');
                    $money -= $order['order_user_pay'];
                    Db::table('up_shops')
                        ->where('s_id', $order['order_shopid'])
                        ->update(['s_money'=>$money]);
                }
            }
            Db::table('up_order')->where($where)->update($update);
            Db::commit();
            //消息和推送
            $user = Db::table('up_order')->where($where)->value('order_userid');
            allInNotice('退款结果通知',$content,$user);
            sendJpush("$user", $content2, array('a' => 'b'), 2, 2, 1);
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }

    //-------------------------------首页的配送--------------------------------------------
    /**
     * 首页展示未开发和已开发的
     * @return string
     */
    public function near()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
//        $lat = '31.97582940293274';
//        $lon = '118.7714203586221';
//        $page = 1;
        $where = array();
        $where['s_status'] = 1;//不能是信用太低的
        $mile = Db::table('up_set_juli')->where('juli_id',3)->value('juli_value');
        $miles = (int)$mile*1000;
        $field = 's_id,s_pinlei_id';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $yess1 = Db::table('up_shops')
            ->field($field)
            ->where($where)
//            ->group('s_pinlei_id')
            ->having("distance <= $miles")
//            ->column('s_pinlei_id');
            ->select();
        $yess2 = array();
        $number = Db::table('up_work_order')
            ->where('o_agree',1)
            ->where('o_status',2)
            ->column('o_number');
        if($number){
            $where2 = array();
            $where2['s_ordernumber'] = array('in',$number);
            $yess2 = Db::table('up_work_shops_copy')
                ->field($field)
                ->where($where2)
//                ->group('s_pinlei_id')
                ->having("distance <= $miles")
                ->select();

        }
        $yess = array_merge($yess1,$yess2);
        $yesdata = array();
        if($yess){
            $yes = array();
            foreach ($yess as $k=>$v){
                $yes[] = $v['s_pinlei_id'];
            }
            $yesdata = Db::table('up_work_pl')
                ->where('pl_id','in',$yes)
                ->select();
            $nodata = Db::table('up_work_pl')
                ->where('pl_id','not in',$yes)
                ->select();
        }else{
            $nodata = Db::table('up_work_pl')->select();
        }
        return json_encode(['status'=>200,'yesdata'=>$yesdata,'nodata'=>$nodata]);
    }
    /**
     * 开发商户
     * @return string
     */
    public function newShopNext()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $shop = Db::table('up_shops')
            ->where('s_phone',$phone)
            ->find();
        $shop2 = Db::table('up_shops')
            ->where('s_bianhao',$bianhao)
            ->find();
        //----------------重复提交--------------
        $re = newShopRepeatRight($phone,$bianhao);
        if($re['status'] != 200){
            return json_encode(['status'=>0,'msg'=>$re['msg']]);
        }
        //-----------重复提交end-------------
        //----------------验证码--------------
        $re = newShopPhonecodeRight($phone,$code);
        if($re['status'] != 200){
            return json_encode(['status'=>0,'msg'=>$re['msg']]);
        }
        //-----------验证码end-------------
        if($shop){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码商户了']);
        }else if($shop2){
            return json_encode(['status'=>0,'msg'=>'已经有此营业执照编号了']);
        }else{
            return json_encode(['status'=>200,'msg'=>'ok']);
        }
    }
    public function newShop()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $shop = Db::table('up_shops')->where('s_phone',$phone)->find();
        if(!empty($shop)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码商户了']);
        }
        //----------------重复提交--------------
        $re = newShopRepeatRight($phone,$bianhao);
        if($re['status'] != 200){
            return json_encode(['status'=>0,'msg'=>$re['msg']]);
        }
        //-----------重复提交end-------------
        Db::startTrans();
        try{
            $number = date('YmdHis') . rand(1000000, 9999999);
            $plname = Db::table('up_work_pl')->where('pl_id',$pinlei_id)->value('pl_name');
            $data = array();
            $data['s_name'] = $name;
            $data['s_pinlei_id'] = $pinlei_id;
            $data['s_pinlei'] = $plname;
            $data['s_bianhao'] = $bianhao;
            $data['s_phone'] = $phone;
            $data['s_beiyongphone'] = $two_phone;
            $data['s_address'] = $address;
            $data['s_lat'] = $lat;
            $data['s_lon'] = $lon;
            $data['s_image'] = trim($image,',');
            $data['s_door'] = trim($door,',');
            $data['s_inside'] = trim($inside,',');
            //------------
            $data['s_zheng'] = trim($zheng,',');
            $data['s_fan'] = trim($fan,',');
            $data['s_shou'] = trim($shou,',');
            if(isset($food)){
                $data['s_food'] = trim($food,',');
            }
            //------------
            $data['s_ordernumber'] = $number;
            $data['s_work_user_id'] = $user_id;
            $data['s_join_in'] = date('Y-m-d');
            $data['s_join_end'] = date("Y-m-d",strtotime("+1 year"));
            Db::table('up_work_shops_copy')->insert($data);
            //算钱
            $allprice = Db::table('up_set_juli')->where('juli_id',4)->value('juli_value');
            $order = array();//TODO
            $order['o_number'] = $number;
            $order['o_user_id'] = $user_id;
            $order['o_level'] = 1;
            $order['o_money'] = 0;
            $order['o_type'] = $type;
            $order['o_user_pay'] = $allprice;
            $order['o_which'] = 2;
            $order['o_date'] = date('Y-m-d');
            $order['o_datetime'] = date('Y-m-d H:i:s');
            Db::table('up_work_order')->insert($order);
            Db::commit();
            //改验证码状态
            Db::table('up_shop_phonecode')->where('phone',$phone)->update(['status'=>1]);
            if($type == 1){
                $respont = $this->getParam($number,'0.01');
                if($respont['status'] == 200){
                    $decodeurl=urldecode($respont['msg']);
                    $a = qrcode($decodeurl);
                    return json_encode(['status'=>200,'msgsss'=>$a,'order_num'=>$number]);
                }else{
                    return json_encode(['status'=>0,'msg'=>$respont['msg']]);
                }
            }else{
                $orderWx = array();
                $orderWx['body'] = '红集';
                $orderWx['total_fee'] = 1;
                $orderWx['out_trade_no'] = $number;
                $orderWx['product_id'] = '';
                $orderWx['trade_type'] = 'NATIVE';
                $respont = $this->WeChatPayReady($orderWx,false,true);
                $decodeurl=urldecode($respont['code_url']);
                $a = qrcode($decodeurl);
                return json_encode(['status'=>200,'msgsss'=>$a,'order_num'=>$number]);
            }
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'保存失败']);
        }
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if ($getInfo) {
            if ($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans();
                try {
                    $number = $getInfo['out_trade_no'];
                    $transaction_id = $getInfo['trade_no'];
                    //2、修改订单状态
                    $update = array();
                    $update['o_status'] = 2;
                    $update['o_transaction_id'] = $transaction_id;
                    Db::table('up_work_order')
                        ->where('o_number', $number)
                        ->update($update);
                    //通知
                    $shopname = Db::table('up_work_shops_copy')
                        ->where('s_ordernumber', $number)
                        ->value('s_name');
                    $userid = Db::table('up_work_order')
                        ->where('o_number', $number)
                        ->value('o_user_id');
                    allInNotice('商户审核','你提交的:'.$shopname.',商户资料正在认证，认证成功后会立刻适配商城，请耐心等待。',$userid);
                    Db::commit();
                    die('success');
                } catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
    public function huidiaoWx()
    {
        $xml=file_get_contents('php://input', 'r');
        $getInfo=$this->toArray($xml);
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign = $this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign === $data_sign && $getInfo['return_code'] == 'SUCCESS' && $getInfo['result_code'] == 'SUCCESS') {
            $number = $getInfo['out_trade_no'];
            $transaction_id = $getInfo['transaction_id'];
            $update = array();
            $update['o_status'] = 2;
            $update['o_transaction_id'] = $transaction_id;
            $res = Db::table('up_work_order')
                ->where('o_number', $number)
                ->update($update);
            //通知
            $shopname = Db::table('up_work_shops_copy')
                ->where('s_ordernumber', $number)
                ->value('s_name');
            $userid = Db::table('up_work_order')
                ->where('o_number', $number)
                ->value('o_user_id');
            allInNotice('商户审核','你提交的:'.$shopname.',商户资料正在认证，认证成功后会立刻适配商城，请耐心等待。',$userid);
            if ($res) {
                $result = $getInfo;
            } else {
                $result = false;
            }
        }else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }

}